<!--
 * @Author: aum
 * @Date: 2021-03-05 16:34:01
 * @LastEditors: aum
 * @LastEditTime: 2021-08-27 19:12:46
 * @Description: 登录
 * @FilePath: \vue3-hand-vant\src\views\tool\Login\index.vue
-->
<template>
  <div>
    <Form @submit="accountLogin">
      <Field
        v-model="state.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <Field
        v-model="state.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <Button block type="primary" native-type="submit"> 提交 </Button>
      </div>
    </Form>
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive } from 'vue'
  import { Button, Form, Field } from 'vant'
  import { useRouter } from 'vue-router'
  import { accountLoginApi } from '@/api/user'
  import { AccountLoginParams, AccountLoginModel } from '@/api/model/user'

  import CryptoJS from 'crypto-js'
  import { userStore } from '@/store/modules/user'

  import { Toast } from 'vant'
  export default defineComponent({
    name: 'Home',
    components: {
      Button,
      Form,
      Field
    },
    setup() {
      const router = useRouter()
      const state = reactive<AccountLoginParams>({
        username: 'XATEST001',
        password: 'Zbxy846840',
        grant_type: 'password'
      })

      const accountLogin = async () => {
        try {
          const password = CryptoJS.SHA256(
            'CRCLDAP+' +
              state.username.toUpperCase() +
              '+' +
              CryptoJS.SHA256(state.password).toString().toUpperCase()
          )
            .toString()
            .toUpperCase()
          const res: AccountLoginModel = await accountLoginApi(
            { ...state, password },
            { showError: true }
          )
          if (res) {
            console.log(`res信息===>`, res)
            userStore.commitUserInfoState(res) // 请求用户信息
            router.push('/tool/home') // 没有获取到用户信息, 跳转登录页面
            Toast({
              message: '登陆成功'
            })
          } else {
            Toast({
              message: '登陆失败'
            })
          }
        } catch (error) {
          console.log(`try错误信息===>`, error)
        }
      }
      return {
        state,
        accountLogin
      }
    }
  })
</script>
